import wsgiref.handlers
import cgi
import os
import urllib
import webob
import Fetch
import Auth
import Mods
from google.appengine.api.urlfetch import fetch
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import datastore
from google.appengine.api import datastore_types



 #MyMod = Mods.PageMod()

def getHTML(qs, request):
      user = users.get_current_user()
      ret=""
      s_qs =  qs  #urllib.unquote(os.environ.get("QUERY_STRING",""))
      if (s_qs==""):
        s_qs = "http://www.google.com"
      s_appPath = request.application_url
      s_fullURL = request.url
      googHTML = ""
      myheader = request.headers 
      if ( s_qs.find("strURL") > 0):
        s_qs=urllib.unquote(s_fullURL[s_fullURL.find("strURL="):].replace("strURL=","") + "?" + s_qs[:s_qs.find("strURL")])
      
      myContent = ""
      myFetch = fetch(s_qs, payload=None, method='GET', allow_truncated=False, follow_redirects=False)
      myContent = myFetch.content
      while myFetch.status_code == 302:
            s_qs=myFetch.headers["location"]
            myFetch = fetch(s_qs, payload=None, method='GET', allow_truncated=False, follow_redirects=False)
            #return request.application_url + "?" + myFetch.headers["location"]


      
      googHTML = myFetch.content
      s_headers = myFetch.headers
      s_status = myFetch.status_code
    
      if myFetch.headers.has_key('location'):
        s_qs = myFetch.headers['location']
      if myFetch.headers.has_key('Location'):
        s_qs = myFetch.headers['Location']
      if myFetch.headers.has_key('host'):
        s_qs = myFetch.headers['host']
      if myFetch.headers.has_key('Host'):
        s_qs = myFetch.headers['Host']
      s_URL = s_qs    
      
  
      s_URLbase = s_qs
      if s_URL.find("/", 8) > 0:
        s_URLbase = s_URL[:(s_URL.find("/", 8))]
        
      
      firstBodyTag = googHTML[googHTML.find("<body"):googHTML.find(">", googHTML.find("<body"))+1]
      #response.out.headers = s_headers
      ret = googHTML.replace("onload","notonload").replace("</title>", "</title><base href='" + s_URLbase + "/'>")
      #self.response.out.write(self.request.headers)
      globalScripts = u""
      m = Mods.Mod()
      dsmm = Mods.DomSpecModMap()
      mgmm = Mods.GlobalModMap()
      allMods = db.GqlQuery("SELECT * FROM Mod").get()
      
      gmms = db.GqlQuery("SELECT * FROM GlobalModMap WHERE user = :1" , user)
      for mgmm in gmms:
            for item in mgmm.globalmodlist:
                  curMod = db.GqlQuery("SELECT * FROM Mod WHERE name = :1", item)
                  if curMod.get():
                        globalScripts = globalScripts + curMod.get().text
      
      dsmms = db.GqlQuery("SELECT * FROM DomSpecModMap WHERE user = :1 AND currentURL = :2", user, s_URLbase.replace("http://", "", 1))
      for dsmm in dsmms:
            for item in dsmm.domSpecMods:
                  curMod = db.GqlQuery("SELECT * FROM Mod WHERE name = :1", item)
                  if curMod.get():
                        globalScripts = globalScripts + "\n" + curMod.get().text
            
      ret = ret.replace("</body>" , """<script>  /**
   * @author philteare
   */
   function errorsuppressor(){
  return true
  }
  window.onerror=errorsuppressor
  
  
  
  if (document.title.indexOf("-_ -") < 0) {
      document.title = "-_ - " + document.title;
      
      var done = 0;
      var strURL = '""" + s_URL + """';
      var strURLbase = '""" + s_URLbase + """';
      var appPath = '""" + s_appPath + """';
  
      
      function convertURL(relURL){
      try {
          var URLIn = relURL.replace("~~~~", "?");
          
          
          
          var path_info = ""
  
          var relPath = relURL;
          if (relPath.indexOf("mailto:") < 0 && relPath.indexOf("http://") < 0 && relPath.indexOf("https://") < 0 && relPath.indexOf("javascript:") < 0) {
          
              if (relPath.indexOf("~___/") >= 0) {
                  //alert(relPath + " " + strURLbase );
                  relPath = relPath.substring(relPath.indexOf("~___")).replace("~___/", "").replace("%22", "");
                  
                  path_info = strURLbase.replace("http://vb1.no-ip.info/VBrowser/", "").replace("http://vb1.no-ip.info/", "").replace("/VBrowser.aspx?", "").replace("~~~~", "?");
              }
              
              if (relPath.indexOf("____/") >= 0) {
              
                  var stump = path_info.substring(0, path_info.lastIndexOf("/") - 1);
                  
                  stump = stump.substring(0, stump.lastIndexOf("/"));
                  path_info = document.strURLbase;
                  
                  relPath = relPath.replace("____/", "/");
                  
              }
              
              
              
              
              // Create the absolute path 
              var absPath = "";
              
              try {
                  absPath = path_info.substring(0, path_info.lastIndexOf("/") + 1);
              } 
              catch (err) {
              }
              absPath += relPath;
              
              
              
              
              // Beautify the path by removing all instances of ./ 
              // and <some dir>/../ except the case of http://<server>/../ 
              var parts = absPath.replace(/\/\.\//g, "/").split("/");
              for (var i = 4; i < parts.length; i++) {
                  if (parts[i] == "..") {
                      for (var j = i + 1; j < parts.length; j++) {
                          parts[j - 2] = parts[j];
                      }
                      parts.length -= 2;
                      i -= 2;
                  }
                  
                  
              }
              absPath = parts.join("/");
              
              // Display result 
              return unescape(absPath);
              
          }
              //alert(relURL);        
          return unescape(relURL);
          }
          catch(err) {return unescape(relURL);}
          
      }
        function sweep(){
          //alert(2);
          if (done == 0) {
              strURL = strURL.replace("~~~~", "?");
             
              
              
              for (var i = 0; i < document.getElementsByTagName("a").length; i++) {
                  if (document.getElementsByTagName("a")[i].style.backgroundImage) {
                      var curBackI = convertURL(document.getElementsByTagName("a")[i].style.backgroundImage).replace("url(", "").replace(")", "");
                      //alert( curBackI);
                      document.getElementsByTagName("a")[i].style.backgroundImage = "url(" + curBackI + ")";
                      
                      //alert( document.getElementsByTagName("a")[i].style.backgroundImage);
                  }
                  
                  if (document.getElementsByTagName("a")[i].href.indexOf("mailto") < 0 && document.getElementsByTagName("a")[i].href.indexOf("javascript:") < 0 ) {
                     if (escape(convertURL(document.getElementsByTagName("a")[i].getAttribute("href"))).indexOf("http")!=0)
                     {document.getElementsByTagName("a")[i].href =  appPath + '?' + document.getElementsByTagName("a")[i].href;}
                     else {document.getElementsByTagName("a")[i].href =  appPath + '?' + document.getElementsByTagName("a")[i].getAttribute("href");}
                  }
              }
              
              
              
              for (var i = 0; i < document.getElementsByTagName("form").length; i++) {
              document.getElementsByTagName("form")[i].method="GET";
                  if (document.getElementsByTagName("form")[i].action.indexOf("javascript:") < 0) {
                    
                      var strURLfield = document.createElement("INPUT");
                      strURLfield.type = "hidden";
                      strURLfield.name = "strURL";
  
                      
                      if (document.getElementsByTagName("form")[i].getAttribute("action").indexOf("http")!=0){
                        strURLfield.value = strURLbase + document.getElementsByTagName("form")[i].getAttribute("action");
                        document.getElementsByTagName("form")[i].action = appPath + "?" + document.getElementsByTagName("form")[i].action;
                      } else {
                        strURLfield.value = document.getElementsByTagName("form")[i].getAttribute("action");
                        document.getElementsByTagName("form")[i].action = appPath + "?" + document.getElementsByTagName("form")[i].action;
                        
                      }
                      document.getElementsByTagName("form")[i].appendChild(strURLfield);
                    }
  
                  
              }
              
              //alert(window.loadedTT);
              
              clearTimeout();
              done = 1;
              
              
              
          }
          else {
          
          }                
      }
      
        loadVBrowser = function(){
      
          var compstate = "";
          try {
              compstate = document.readyState;
          } 
          catch (err) {
          }
          window.status = compstate;
          
          if (window.document && window.document.body) {
          
          try {
              sweep();
           }
           catch(err){}
           """ +  globalScripts.encode('utf8')  + """
          }
          else {
              setTimeout("loadVBrowser()", 150);
          }
          
      }
      
      setTimeout("loadVBrowser()", 150);
      
      }
      </script></body>""", 1)
      

      return ret
   